package com.czy.owner.ui.workorder;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.czy.owner.R;
import com.czy.owner.adapter.MyOrderDetailCustomAdapter;
import com.czy.owner.adapter.MyOrderDetailGoodAdapter;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.MyOrderDetailModel;
import com.czy.owner.global.Constants;
import com.czy.owner.net.utils.JsonUtil;
import com.czy.owner.permission.Acp;
import com.czy.owner.permission.AcpListener;
import com.czy.owner.permission.AcpOptions;
import com.czy.owner.rxbus.RxBus;
import com.czy.owner.rxbus.Subscribe;
import com.czy.owner.rxbus.ThreadMode;
import com.czy.owner.rxbus.event.CommonEvent;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.SharedPreferencesUtils;
import com.czy.owner.utils.TimeUtils;
import com.czy.owner.widget.CustomAndGoodDecoration;
import com.czy.owner.widget.FullyLinearLayoutManager;
import com.czy.owner.widget.MyRecyclerView;
import com.czy.owner.widget.StepsView;
import com.czy.owner.widget.UniversalDialog;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by wangyang on 2017/3/20 0020.
 * 订单详情
 */
public class OrderDetailActivity2 extends BaseActivity {

    @BindView(R.id.tv_order_number)
    TextView tvOrderNumber;//订单号
    @BindView(R.id.tv_order_status)
    TextView tvOrderStatus;//订单状态

    //中间
    @BindView(R.id.order_service_list)
    TextView tvOrderService;//预约项目
    @BindView(R.id.order_service_time)
    TextView tvOrderServiceTime;//服务时间
    @BindView(R.id.order_emps)
    TextView tvOrderEmps;//服务技师

    @BindView(R.id.ll_paid_type)
    LinearLayout llPaidType;//已付定金和已付尾款  显示隐藏
    @BindView(R.id.order_paid_type)
    TextView tvOrderPaidType;//已付定金和已付尾款  标题
    @BindView(R.id.order_paid_amount)
    TextView tvOrderPaidAmount;//已付定金和已付尾款  金额

    @BindView(R.id.order_note)
    TextView tvOrderNote;//其他说明


    @BindView(R.id.line_good)
    LinearLayout lineGood;//显示隐藏商品
    @BindView(R.id.line_custom)
    LinearLayout lineCustom;//显示隐藏自定义项目
    @BindView(R.id.recyclerView_good)
    MyRecyclerView recycleViewGood;//商品rv
    @BindView(R.id.recyclerView_custom)
    MyRecyclerView recycleViewCustom;//自定义rv

    @BindView(R.id.order_create_time)
    TextView tvOrderOreateTime;//提交时间

    @BindView(R.id.relative_bottom)
    RelativeLayout relativeBottom;//底部状态
    @BindView(R.id.order_paystatus)
    TextView tvOrderPayStatus;//订金
    @BindView(R.id.btn_paid)
    Button btnPaid;//立即支付


    private String orderNumber;
    private String orderStatus;//订单状态


    //////////////////////////////////
    @BindView(R.id.tv_stay_paid)
    TextView tvStayPaid;//待付定金
    @BindView(R.id.tv_stay_service)
    TextView tvStayService;//待服务
    @BindView(R.id.tv_stay_endofpayment)
    TextView tvStayEndofpayment;//待付尾款
    @BindView(R.id.tv_hasended)
    TextView tvHasended;//已结束
    @BindView(R.id.stepsView)
    StepsView mStepsView;//订单流程
    private final String[] labels = new String[4];


    private MyOrderDetailModel model = null;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_my_order_detail;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        orderNumber = getIntent().getStringExtra("orderNumber");
        if (TextUtils.isEmpty(orderNumber)) {
            PhoneUtils.ShowToastMessage(OrderDetailActivity2.this, "参数异常");
            finish();
            return;
        }
        getToolbarTitle().setText(R.string.order_detail);
        RxBus.getDefault().register(this);
        getOrderDetail();
        stepView(0);
    }

    @Override
    protected void updateViews() {

    }


    private void getOrderDetail() {
        mLoadView.ShowLoadView();
        String url = Constants.APP_API_BASE + Constants.OWN_ORDER_MYORDERINF;
        RequestParams params = new RequestParams(url);
        params.addBodyParameter("session", UserHelper.getInstance().getSessionInfoModel(OrderDetailActivity2.this).getSession());
        params.addBodyParameter("orderNumber", orderNumber);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                MyLog.e("yang", "订单详情成功==" + result);
                String data = PhoneUtils.checkResponseFlag(OrderDetailActivity2.this, result);
                if (data != null) {

                    Gson gson = new GsonBuilder().create();
                    model = gson.fromJson(data, MyOrderDetailModel.class);
                    tvOrderNumber.setText("订单号: " + model.getOrderNumber());
                    tvOrderService.setText(model.getServiceList());
                    String servicetime = TimeUtils.formatTimeDifference2(model.getServiceTime());
                    tvOrderServiceTime.setText(servicetime);
                    tvOrderEmps.setText(model.getOrderEmps());
                    tvOrderNote.setText(model.getNote());
                    String createtime = TimeUtils.formatTimeDifference2(model.getCreateTime());
                    tvOrderOreateTime.setText(createtime);

                    orderStatus = model.getOrderStatus();

                    if (orderStatus.equals("created")) {

                        stepView(0);
                        tvOrderStatus.setText("待处理");
                        getSubTitle().setText("取消预约");
                        llPaidType.setVisibility(View.GONE);
                        relativeBottom.setVisibility(View.GONE);
                        lineGood.setVisibility(View.GONE);
                        lineCustom.setVisibility(View.GONE);

                    } else if (orderStatus.equals("waitPayDeposit")) {
                        stepView(0);
                        tvOrderStatus.setText("待付定金");
                        getSubTitle().setText("取消预约");
                        llPaidType.setVisibility(View.GONE);
                        relativeBottom.setVisibility(View.VISIBLE);
                        tvOrderPayStatus.setText("订金: ￥" + String.format("%.2f", model.getActualDepositAmount()));
                        //lineGood.setVisibility(View.GONE);
                        //lineCustom.setVisibility(View.GONE);
                        goodCustomList(model.getGoodsItemList(), model.getCustomItemList());
                    } else if (orderStatus.equals("waitService")) {

                        stepView(1);
                        tvOrderStatus.setText("待服务");
                        getSubTitle().setText("取消预约");
                        llPaidType.setVisibility(View.VISIBLE);
                        tvOrderPaidAmount.setText("￥" + String.format("%.2f", model.getActualDepositAmount()));
                        relativeBottom.setVisibility(View.GONE);
                        goodCustomList(model.getGoodsItemList(), model.getCustomItemList());

                    } else if (orderStatus.equals("inService")) {

                        stepView(2);
                        tvOrderStatus.setText("服务中");
                        getSubTitle().setVisibility(View.GONE);
                        llPaidType.setVisibility(View.VISIBLE);
                        tvOrderPaidAmount.setText("￥" + String.format("%.2f", model.getActualDepositAmount()));
                        relativeBottom.setVisibility(View.GONE);
                        goodCustomList(model.getGoodsItemList(), model.getCustomItemList());

                    } else if (orderStatus.equals("inSettlement")) {

                        stepView(2);
                        tvOrderStatus.setText("服务完成");
                        getSubTitle().setVisibility(View.GONE);
                        llPaidType.setVisibility(View.VISIBLE);
                        tvOrderPaidAmount.setText("￥" + String.format("%.2f", model.getActualDepositAmount()));
                        relativeBottom.setVisibility(View.VISIBLE);
                        tvOrderPayStatus.setText("尾款: ￥" + String.format("%.2f", model.getPayAmount()));
                        btnPaid.setText("支付尾款");
                        goodCustomList(model.getGoodsItemList(), model.getCustomItemList());

                    } else if (orderStatus.equals("hasPayed")) {

                        stepView(3);
                        tvOrderStatus.setText("已付尾款");
                        getSubTitle().setText("删除订单");
                        llPaidType.setVisibility(View.VISIBLE);
                        tvOrderPaidType.setText("总计金额:");
                        tvOrderPaidAmount.setText("￥" + String.format("%.2f", model.getTotalPrice()));
                        relativeBottom.setVisibility(View.GONE);
                        goodCustomList(model.getGoodsItemList(), model.getCustomItemList());

                    } else if (orderStatus.equals("completed")) {

                        stepView(3);
                        tvOrderStatus.setText("已完成");
                        getSubTitle().setText("删除订单");
                        llPaidType.setVisibility(View.VISIBLE);
                        tvOrderPaidType.setText("总计金额:");
                        tvOrderPaidAmount.setText("￥" + String.format("%.2f", model.getTotalPrice()));
                        relativeBottom.setVisibility(View.VISIBLE);
                        btnPaid.setText("立即评价");
                        btnPaid.setBackgroundResource(R.drawable.selector_order_btn_has_ended);
                        btnPaid.setTextColor(getResources().getColor(R.color.order_tv_color));
                        goodCustomList(model.getGoodsItemList(), model.getCustomItemList());

                    } else if (orderStatus.equals("commented")) {

                        stepView(3);
                        tvOrderStatus.setText("已评价");
                        getSubTitle().setText("删除订单");
                        llPaidType.setVisibility(View.VISIBLE);
                        tvOrderPaidType.setText("总计金额:");
                        tvOrderPaidAmount.setText("￥" + String.format("%.2f", model.getTotalPrice()));
                        relativeBottom.setVisibility(View.VISIBLE);
                        btnPaid.setText("查看评价");
                        btnPaid.setBackgroundResource(R.drawable.selector_order_btn_has_ended);
                        btnPaid.setTextColor(getResources().getColor(R.color.order_tv_color));
                        goodCustomList(model.getGoodsItemList(), model.getCustomItemList());

                    } else if (orderStatus.equals("cancelled")) {

                        stepView(3);
                        tvOrderStatus.setText("已取消");
                        getSubTitle().setText("删除订单");
                        llPaidType.setVisibility(View.VISIBLE);
                        tvOrderPaidType.setText("总计金额:");
                        tvOrderPaidAmount.setText("￥" + String.format("%.2f", model.getTotalPrice()));
                        relativeBottom.setVisibility(View.GONE);
                        goodCustomList(model.getGoodsItemList(), model.getCustomItemList());

                    }
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                MyLog.e("yang", "订单详情失败==" + ex.toString());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                mLoadView.CancleLoadView();
            }
        });
    }


    @OnClick(R.id.btn_paid)
    public void btnPaidOnClick(View view) {
        String btnText = btnPaid.getText().toString().trim();

        if (btnText.equals("立即支付")) {
            Intent ti = new Intent(OrderDetailActivity2.this, PaidSubscriptionActivity.class);
            ti.putExtra("orderNumber", model.getOrderNumber());
            ti.putExtra("storeId", model.getStoreId());
            startActivity(ti);
        } else if (btnText.equals("支付尾款")) {
            Intent ti = new Intent(OrderDetailActivity2.this, PaidEndOfPaymentActivity.class);
            ti.putExtra("orderNumber", model.getOrderNumber());
            ti.putExtra("storeId", model.getStoreId());
            startActivity(ti);
        } else if (btnText.equals("立即评价")) {
            Intent ti = new Intent(OrderDetailActivity2.this, EvaluateActivity2.class);
            ti.putExtra("orderNumber", model.getOrderNumber());
            ti.putExtra("storeId", model.getStoreId());
            startActivity(ti);
        } else if (btnText.equals("查看评价")) {
            Intent ti = new Intent(OrderDetailActivity2.this, SeeEvaluateActivity2.class);
            ti.putExtra("orderNumber", model.getOrderNumber());
            ti.putExtra("storeId", model.getStoreId());
            startActivity(ti);
        }

    }


    private void goodCustomList(List<MyOrderDetailModel.GoodsItemListBean> orderGoodItemList, List<MyOrderDetailModel.CustomItemListBean> orderCustomItemList) {
        TypedValue mTmpValue1 = new TypedValue();
        getResources().getValue(R.dimen.app_theme_border_stroke, mTmpValue1, true);
        TypedValue mTmpValue2 = new TypedValue();
        getResources().getValue(R.dimen.app_theme_border_stroke, mTmpValue2, true);

        if (orderGoodItemList.size() == 0) {
            lineGood.setVisibility(View.GONE);
        } else {
            lineGood.setVisibility(View.VISIBLE);
            FullyLinearLayoutManager layoutManager = new FullyLinearLayoutManager(OrderDetailActivity2.this);
            recycleViewGood.setLayoutManager(layoutManager);
            recycleViewGood.addItemDecoration(new CustomAndGoodDecoration(OrderDetailActivity2.this, TypedValue.complexToFloat(mTmpValue1.data), TypedValue.complexToFloat(mTmpValue2.data), R.color.appThemeBorderColor));
            recycleViewGood.setAdapter(new MyOrderDetailGoodAdapter(OrderDetailActivity2.this, orderGoodItemList));
        }

        if (orderCustomItemList.size() == 0) {
            lineCustom.setVisibility(View.GONE);
        } else {
            lineCustom.setVisibility(View.VISIBLE);
            FullyLinearLayoutManager layoutManager = new FullyLinearLayoutManager(OrderDetailActivity2.this);
            recycleViewCustom.setLayoutManager(layoutManager);
            recycleViewCustom.addItemDecoration(new CustomAndGoodDecoration(OrderDetailActivity2.this, TypedValue.complexToFloat(mTmpValue1.data), TypedValue.complexToFloat(mTmpValue2.data), R.color.appThemeBorderColor));
            recycleViewCustom.setAdapter(new MyOrderDetailCustomAdapter(OrderDetailActivity2.this, orderCustomItemList));
        }
    }

    @OnClick(R.id.toolbar_subtitle)
    public void tvTitleRightOnClick(View view) {
        if (orderStatus.equals("created") || orderStatus.equals("waitPayDeposit")) {
            cancleYuYueDialog("您确定要取消预约吗?", "去意已决", "我再想想");
        } else if (orderStatus.equals("waitService")) {
            //StoreDetailInfoModel infoModel = GsonUtils.getBean((String) SharedPreferencesUtils.getParam(OrderDetailActivity.this, Constants.SHARED_PREFERENCES_KEY_HOME_STORE_INFO, ""), StoreDetailInfoModel.class);
            String phone = model.getServiceNumber();
            cancleYuYueDialogCall("要取消预约,要先联系商家哦!\n商家电话" + phone, "确定拨打", "我再想想", phone);
        } else if (orderStatus.equals("completed") || orderStatus.equals("commented") || orderStatus.equals("cancelled") || orderStatus.equals("hasPayed")) {
            deleteOrderDialog("删除订单", "确定", "取消");
        }


    }

    //取消订单
    private void cancleYuYueDialog(String title, String sure, String cancle) {
        new UniversalDialog(OrderDetailActivity2.this).builder().setTitle(title)

                .setPositiveButton(sure, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        cancleYuYueOrder();
                    }
                }).setNegativeButton(cancle, new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        }).show();
    }

    private void cancleYuYueOrder() {
        mLoadView.ShowLoadView();
        String url = Constants.APP_API_BASE + Constants.OWN_ORDER_CANCLE;
        RequestParams params = new RequestParams(url);
        params.addBodyParameter("session", UserHelper.getInstance().getSessionInfoModel(OrderDetailActivity2.this).getSession());
        params.addBodyParameter("storeId", model.getStoreId() + "");
        params.addBodyParameter("userOrderId", model.getUserOrderId() + "");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                MyLog.e("yang", "取消订单成功onSuccess==" + result);
                String flag = JsonUtil.getJsonValuesString(result, "flag");
                String exp = JsonUtil.getJsonValuesString(result, "exp");
                if (flag.equals("true")) {
                    Intent intent = new Intent();
                    intent.setAction(SubscribeOrdelActivity.orderAction);
                    if (orderStatus.equals("created")) {
                        intent.putExtra("currentId", 4);
                    } else if (orderStatus.equals("waitPayDeposit")) {
                        intent.putExtra("currentId", 4);
                    }
                    sendBroadcast(intent);
                    finish();
                } else {
                    PhoneUtils.ShowToastMessage(OrderDetailActivity2.this, exp);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                MyLog.e("yang", "取消订单失败onError==" + ex.toString());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                mLoadView.CancleLoadView();
            }
        });

    }
//打电话取消订单

    private void cancleYuYueDialogCall(String title, String sure, String cancle, final String phone) {
        new UniversalDialog(OrderDetailActivity2.this).builder().setTitle(title)
                .setPositiveButton(sure, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if ((Build.VERSION.SDK_INT >= 23)) {
                            onClickCallPhone(phone);
                        } else {
                            Intent intent = new Intent();
                            intent.setAction(Intent.ACTION_CALL);
                            intent.setData(Uri.parse("tel:" + phone));
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                        }

                    }
                }).setNegativeButton(cancle, new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        }).show();
    }

    public void onClickCallPhone(final String phone) {
        Acp.getInstance(this).request(new AcpOptions.Builder().setPermissions(Manifest.permission.CALL_PHONE).build(),
                new AcpListener() {
                    @Override
                    public void onGranted() {
                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_CALL);
                        intent.setData(Uri.parse("tel:" + phone));
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                    }

                    @Override
                    public void onDenied(List<String> permissions) {
                        PhoneUtils.ShowToastMessage(OrderDetailActivity2.this, permissions.toString() + "权限拒绝");

                    }
                });

    }
//删除订单

    private void deleteOrderDialog(String title, String sure, String cancle) {
        new UniversalDialog(OrderDetailActivity2.this).builder().setTitle(title)
                .setPositiveButton(sure, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        deleteOrder();


                    }
                }).setNegativeButton(cancle, new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        }).show();
    }

    private void deleteOrder() {
        String url = Constants.APP_API_BASE + Constants.OWN_ORDER_ORDERDELORDE;
        RequestParams params = new RequestParams(url);
        params.addBodyParameter("session", UserHelper.getInstance().getSessionInfoModel(OrderDetailActivity2.this).getSession());
        params.addBodyParameter("storeId", SharedPreferencesUtils.getParam(OrderDetailActivity2.this, UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_BINDSTOREID, 0) + "");
        params.addBodyParameter("orderNumber", model.getOrderNumber());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    String data = PhoneUtils.checkResponseFlag(OrderDetailActivity2.this, result);
                    if (data != null) {
                        Intent intent = new Intent();
                        intent.setAction(SubscribeOrdelActivity.orderAction);
                        if (SubscribeOrdelActivity.currentId() == 0) {
                            intent.putExtra("currentId", 0);
                        } else if (SubscribeOrdelActivity.currentId() == 4) {
                            intent.putExtra("currentId", 4);
                        }
                        sendBroadcast(intent);
                        finish();
                    }
                } catch (Exception e) {

                }


            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }


    @Subscribe(code = Constants.ORDER_PAID_SUCCESS, threadMode = ThreadMode.MAIN)
    public void eventOrderPaidSuccess(CommonEvent orderpaidSuccessEvent) {
        finish();
    }


    @Subscribe(code = Constants.PAID_SUCCESS_ENDOF_PAYMENT, threadMode = ThreadMode.MAIN)
    public void eventPaidEndofSuccess(CommonEvent paidEndOfSuccessEvent) {
        finish();
    }

    @Subscribe(code = Constants.EVALUATE_SUCCESS, threadMode = ThreadMode.MAIN)
    public void eventEvaluateSuccess(CommonEvent evaluateSuccessEvent) {
        finish();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        RxBus.getDefault().unRegister(this);

    }

    private void stepView(int current) {
        mStepsView.setCompletedPosition(current)
                .setLabels(labels)
                .setBarColorIndicator(
                        getResources().getColor(R.color.message_list_decoration))
                .setProgressColorIndicator(getResources().getColor(R.color.appThemeColor))
                .setLabelColorIndicator(getResources().getColor(R.color.appThemeColor))
                .drawView();
        setTextColor(current);
    }

    private void setTextColor(int currentPos) {
        if (currentPos == 0) {
            tvStayPaid.setTextColor(getResources().getColor(R.color.appThemeColor));
        } else if (currentPos == 1) {
            tvStayPaid.setTextColor(getResources().getColor(R.color.appThemeColor));
            tvStayService.setTextColor(getResources().getColor(R.color.appThemeColor));
        } else if (currentPos == 2) {
            tvStayPaid.setTextColor(getResources().getColor(R.color.appThemeColor));
            tvStayService.setTextColor(getResources().getColor(R.color.appThemeColor));
            tvStayEndofpayment.setTextColor(getResources().getColor(R.color.appThemeColor));
        } else if (currentPos == 3) {
            tvStayPaid.setTextColor(getResources().getColor(R.color.appThemeColor));
            tvStayService.setTextColor(getResources().getColor(R.color.appThemeColor));
            tvStayEndofpayment.setTextColor(getResources().getColor(R.color.appThemeColor));
            tvHasended.setTextColor(getResources().getColor(R.color.appThemeColor));
        }
    }
}
